package com.example.tianling.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.example.tianling.common.utils.RedisUtils;
import com.example.tianling.entity.UserEntity;
import com.example.tianling.service.UserService;
import com.example.tianling.service.WxService;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxServiceImpl implements WxService {
    @Autowired
    private RedisUtils redisUtils;

//    @Autowired
//    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(WxService.class);
    private static final String appid = "wxc6a889e9386054ac";
    private static final String secret = "6f78e56e398173d391240383c2541a89";

    @Override
    public String getAccessToken() throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")
                .url(url)
                .build();

        Response response = client.newCall(request).execute();

        if (response.body() != null) {
            JSONObject responseJson = JSONObject.parseObject(response.body().string());
            return responseJson.getString("access_token");
        }
        return null;
    }

    @Override
    public String getOpenId(String code) throws IOException {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")
                .url(url)
                .build();

        Response response = client.newCall(request).execute();

        if (response.body() != null) {
            JSONObject responseJson = JSONObject.parseObject(response.body().string());
            String openId = responseJson.getString("openid");

            return openId;
        }
        return null;
    }

    @Override
    public String getPhoneNumber(String code) throws IOException {
        // 获取鉴权accessToken
        String accessToken = redisUtils.get("accessToken");
        if (accessToken == null) {
            accessToken = getAccessToken();
            redisUtils.set("accessToken", accessToken, 60*60);
        }

        // 请求用户的手机号码
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken;

        OkHttpClient client = new OkHttpClient();

        JSONObject requestJson = new JSONObject();
        requestJson.put("code", code);
        RequestBody body = RequestBody.create(requestJson.toString(), MediaType.parse("application/json;charset=utf-8"));

        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")
                .url(url)
                .post(body)
                .build();

        Response response = client.newCall(request).execute();

        // 检查返回的phoneNumber
        if (response.body() != null) {
            JSONObject responseJson = JSONObject.parseObject(response.body().string());
            System.out.println(responseJson);
            JSONObject phoneInfo = (JSONObject) responseJson.get("phone_info");
            return phoneInfo.getString("phoneNumber");
        }

        return null;
    }

    @Override
    public boolean textCheck(String openId, String content, int scene) throws IOException {
        // 获取鉴权accessToken
        String accessToken = redisUtils.get("accessToken");
        if (accessToken == null) {
            accessToken = getAccessToken();
            redisUtils.set("accessToken", accessToken, 60*60);
        }

        // 发起文本内容核查请求
        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token="+accessToken;

        OkHttpClient client = new OkHttpClient();

        JSONObject requestJson = new JSONObject();
        requestJson.put("content", content);
        requestJson.put("version", 2);
        requestJson.put("scene", scene);
        requestJson.put("openid", openId);
        RequestBody body = RequestBody.create(requestJson.toString(), MediaType.parse("application/json;charset=utf-8"));

        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")
                .url(url)
                .post(body)
                .build();

        Response response = client.newCall(request).execute();

        // 检查返回的标签 label
        if (response.body() != null) {
            JSONObject responseJson = JSONObject.parseObject(response.body().string());
            JSONObject result = (JSONObject) responseJson.get("result");
            int label = result.getInteger("label");
            return label == 100;
        }
        return false;
    }

    @Override
    public String mediaCheck(String openId, String mediaUrl, int mediaType, int scene) throws IOException {
        // 获取鉴权accessToken
        String accessToken = redisUtils.get("accessToken");
        if (accessToken == null) {
            accessToken = getAccessToken();
            redisUtils.set("accessToken", accessToken, 60*60);
        }

        // 发起媒体内容核查请求
        String url = "https://api.weixin.qq.com/wxa/media_check_async?access_token="+accessToken;

        OkHttpClient client = new OkHttpClient();

        JSONObject requestJson = new JSONObject();
        requestJson.put("media_url", mediaUrl);
        requestJson.put("media_type", mediaType);
        requestJson.put("version", 2);
        requestJson.put("scene", scene);
        requestJson.put("openid", openId);
        RequestBody body = RequestBody.create(requestJson.toString(), MediaType.parse("application/json;charset=utf-8"));

        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")
                .url(url)
                .post(body)
                .build();

        Response response = client.newCall(request).execute();

        // 返回traceId
        String traceId = "";
        if (response.body() != null) {
            JSONObject responseJson = JSONObject.parseObject(response.body().string());
            if (responseJson.getInteger("errcode").equals(0)) {
                traceId = responseJson.getString("trace_id");
            }
        }
        return traceId;
    }


}
